package com.ssy.lingxi.marketing.serviceimpl;

import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.marketing.model.vo.common.response.PageItemVO;
import com.ssy.lingxi.marketing.service.ICommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 公共服务 - 业务实现层
 * @author ds
 * @version 2.0.0
 * @date 2021/06/17
 */
@Slf4j
@Service
public class CommonServiceImpl implements ICommonService {

    /**
     * 获取枚举状态列表值.
     * @param cls 枚举类型Class
     * @return 页面下拉菜单项列表
     */
    @Override
    public Wrapper<List<PageItemVO>> getStatusList(Class<?> cls) {
        return getStatusList(cls, null);
    }

    @Override
    public Wrapper<List<PageItemVO>> getStatusList(Class<?> cls, List<Integer> excludeIds) {
        List<PageItemVO> itemVOS = null;
        if (cls.isEnum()) {
            Object[] enumConstants = cls.getEnumConstants();
            try {
                Method getCode = cls.getMethod("getCode", (Class<?>[]) null);
                Method getMessage = cls.getMethod("getMessage", (Class<?>[]) null);
                itemVOS = new ArrayList<>();
                for (Object enumConstant : enumConstants) {
                    Integer code = (Integer) getCode.invoke(enumConstant);
                    String message = (String) getMessage.invoke(enumConstant);
                    if (excludeIds != null && excludeIds.contains(code)) {
                        continue;
                    }
                    PageItemVO vo = new PageItemVO();
                    vo.setStatus(code);
                    vo.setName(message);
                    itemVOS.add(vo);
                }
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                log.error("获取枚举状态值列表异常：", e);
            }
        }
        return Wrapper.success(itemVOS);
    }
}
